package com.tiennt.android.callnotes;

import com.tiennt.android.callnotes.db.DbAdapter;
import com.tiennt.android.callnotes.utils.ProjectUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class AddNoteActivity extends Activity {

	// Component
	private EditText txtNoteTitle;
	private EditText txtNoteContent;
	private Button btnSave;
	private Button btnCancel;
	private Button btnSelectContact;
	private TextView tvContact;
	private CheckBox chbxIncoming;
	private CheckBox chbxOutgoing;

	private static final int CONTACT_PICKER_RESULT = 1001;
	private final String TAG = "AddNoteActivity";
	private final boolean DBG = true;

	// Variable handle content of each component
	private String noteTitle = "";
	private String noteContent = "";
	private String contactId = "";
	private int incoming;
	private int outgoing;
	private View.OnClickListener onBtnSaveClick;
	private View.OnClickListener onBtnCancelClick;
	private View.OnClickListener onBtnSelectContactClick;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_note);

		initialComponents();
	}

	private void initialComponents() {
		txtNoteTitle = (EditText) findViewById(R.id.txtNoteTitle);
		txtNoteContent = (EditText) findViewById(R.id.txtNoteContent);

		btnSave = (Button) findViewById(R.id.btnSave);
		btnCancel = (Button) findViewById(R.id.btnCancel);
		btnSelectContact = (Button) findViewById(R.id.btnChangeContact);

		tvContact = (TextView) findViewById(R.id.tvContact);

		chbxIncoming = (CheckBox) findViewById(R.id.chbxIncomming);
		chbxOutgoing = (CheckBox) findViewById(R.id.chbxOutgoing);

		onBtnSaveClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				handleOnBtnSaveClick();
			}
		};

		onBtnCancelClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				handleOnBtnCancelClick();
			}
		};

		onBtnSelectContactClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				handleOnBtnSelectContactClick();
			}
		};

		btnSave.setOnClickListener(onBtnSaveClick);
		btnCancel.setOnClickListener(onBtnCancelClick);
		btnSelectContact.setOnClickListener(onBtnSelectContactClick);

		Bundle data = getIntent().getExtras();
		if (data != null) {
			contactId = data.getString(ProjectUtils.BUNDLEKEY_CONTACTID);
			tvContact.setText(data
					.getString(ProjectUtils.BUNDLEKEY_CONTACTNAME));
		}
	}

	private void handleOnBtnSaveClick() {
		noteTitle = txtNoteTitle.getText().toString();
		noteContent = txtNoteContent.getText().toString();

		incoming = chbxIncoming.isChecked() == true ? 1 : 0;
		outgoing = chbxOutgoing.isChecked() == true ? 1 : 0;

		if (noteTitle.equals("") && noteContent.equals("")) {
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setTitle("");
			alert.setMessage("You must set at least title or content!!!");
			alert.setNeutralButton("OK", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub

				}
			});
			alert.create().show();
		} else if (contactId.equals("")) {
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setTitle("");
			alert.setMessage("You must choose one contact for this note!!!");
			alert.setNeutralButton("OK", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub

				}
			});
			alert.create().show();
		} else {
			saveNote();
		}
	}

	@Override
	public void onBackPressed() {
		promptOnFinish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case CONTACT_PICKER_RESULT:
				// handle contact results
				String contactName = "";
				Cursor cursor = null;
				try {
					Uri result = data.getData();
					log("Got a contact result: " + result.toString());
					// get the contact id from the Uri
					contactId = result.getLastPathSegment();
					log(contactId);
					log("Got a contact result: " + contactId);

					Uri contactUri = ContentUris.withAppendedId(
							ContactsContract.Contacts.CONTENT_URI,
							Long.parseLong(contactId));

					cursor = managedQuery(contactUri, null, null, null, null);

					if (cursor.moveToFirst()) {
						contactName = cursor
								.getString(cursor
										.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
					}
				} catch (Exception e) {
					// TODO: handle exception
					log("Unexpected exception occurred");
				}

				tvContact.setText(contactName);
				break;
			}
		} else {
			// gracefully handle failure
			log("Warning: activity result not ok");
		}
	}

	private void handleOnBtnCancelClick() {
		promptOnFinish();
	}

	private void handleOnBtnSelectContactClick() {
		Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
				Contacts.CONTENT_URI);
		startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);

	}

	private void saveNote() {
		int result = 0;
		DbAdapter dbAdapter = new DbAdapter(AddNoteActivity.this);
		dbAdapter.open();

		result = (int) dbAdapter.saveNote(noteTitle, noteContent, contactId,
				incoming, outgoing, 1);

		dbAdapter.close();

		if (result != -1) {
			setResult(RESULT_OK);
			Toast.makeText(getApplicationContext(), "Success",
					Toast.LENGTH_SHORT).show();
			this.finish();
		} else {
			Toast.makeText(getApplicationContext(), "Failure",
					Toast.LENGTH_SHORT).show();
		}
	}

	private void promptOnFinish() {
		if (!txtNoteTitle.getText().toString().equals("")
				|| !txtNoteContent.getText().toString().equals("")) {

			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setTitle("Discard?");
			alert.setMessage("Your changes are unsaved. Do you want to save the note?");

			alert.setPositiveButton("Yes",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							// Save the note
							saveNote();
						}
					});

			alert.setNegativeButton("No",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							setResult(RESULT_CANCELED);
							AddNoteActivity.this.finish();
						}
					});
			alert.create().show();
		} else {
			AddNoteActivity.this.finish();
		}
	}

	public void log(String msg) {
		if (DBG) {
			Log.d(TAG, msg);
		}
	}
}
